package com.sun.study.utils;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author Sun
 * @Date 2020/4/11 22:16
 * @Version 1.0
 */
public class jdbcUtils_DBCP {

    //提升作用域
    private static DataSource dataSource = null;

    static {

        try {
            //通过本类的类加载器获得properties文件的资源输入流
            InputStream in = jdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcp_config.properties");

            //创建一个properties对象
            Properties properties = new Properties();
            properties.load(in);

            //创建数据源，工厂模式--获取对象
            dataSource = BasicDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //返回连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();//从数据源中获取连接
    }

    //释放连接
    public static void Release(Connection con, Statement st, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
